import React, { Component, Fragment } from "react";
import "./style.css";
import TodoItem from "./TodoItem";

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: "",
      list: []
    };
    this.handleInputValue = this.handleInputValue.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleItemDelete = this.handleItemDelete.bind(this);
  }

  render() {
    return (
      <Fragment>
        <div>
          <label htmlFor="insertArea">请输入内容</label>
          <input
            id="insertArea"
            className="input"
            value={this.state.inputValue}
            onChange={this.handleInputValue}
          />
          <button onClick={this.handleBtnClick}>提交</button>
        </div>
        <ul>{this.getTodoItem()}</ul>
      </Fragment>
    );
  }

  getTodoItem() {
    return this.state.list.map((item, idx) => {
      return (
        <TodoItem
          key={idx}
          idx={idx}
          content={item}
          deleteItem={this.handleItemDelete}
        />
      );
    });
  }

  handleInputValue(e) {
    // react要改变数据必须用setState方法
    const value = e.target.value;
    this.setState(() => ({
      inputValue: value
    }));
  }

  handleBtnClick() {
    this.setState((prevState) => ({
      list: [...prevState.list, prevState.inputValue],
      inputValue: ""
    }));
  }

  handleItemDelete(idx) {
    this.setState((prevState) => {
      let list = [...prevState.list];
      list.splice(idx, 1);
      return {list}
    });
  }
}

export default TodoList;
